package com.ims.iaa.AD;
import com.ims.iaa.IaaDebug; 
import com.ims.iaa.IaaUtil; 
//
// Copyright: MetaPlus Inc & Inquiry Management Systems Ltd.  2000
//
// Author: Michael Liao
//
// References: 
//    Netscape's Preliminary Specification
//     http://www.netscape.com/newsref/std/cookie_spec.html
//	 RFC 2109 
//     ftp://ftp.isi.edu/in-notes/rfc2109.txt
//
//

import java.net.*;
import java.util.*;

/**
 * A very simple cookie.<br> 
 * This is not a complete solution. It does not handle any "domain", "path", 
 * "expires" information. Right now, it just store where it comes from and cookies 
 * value it contains.When it being sent out, it will make sure the target host 
 * match the original host, otherwise, nothing will be sent out.<br><br>
 *
 * So, it should <b>NOT</b> be store in any physical storage for further using.<br><br>
 *
 * For comprehensive solution, please refer to the following references:<br><br>
 *   <a href="http://www.netscape.com/newsref/std/cookie_spec.html">Netscape's Preliminary Specification</a><br>
 *   <a href="ftp://ftp.isi.edu/in-notes/rfc2109.txt">RFC 2109</a>
 */
public class SimpleCookies {

	// where this cookie came from
	String srcHost = null;
	// cookie's name-value pair string
	Hashtable cookies = new Hashtable();
	
	/**
	 * Read cookies from a connection.
	 */
	public void readCookies( URLConnection urlConn ) {
		
		String hdrKey;
		String hdrValue;
		String aCookie;
		for (int i=1; (hdrKey = urlConn.getHeaderFieldKey(i)) != null; i++) {
			if (hdrKey.equals("Set-Cookie")) {
				if (srcHost == null) {
					//save the srcHost, for comparation when sending this cookie 
					URL url = urlConn.getURL();
					srcHost = url.getHost();
				}
				hdrValue = urlConn.getHeaderField(i);
				//IaaUtil.log( "receive a cookie: " + hdrValue );
				int idx = hdrValue.indexOf(";");
				if ( idx != -1 )  {
					aCookie = hdrValue.substring(0, idx );
					int j = aCookie.indexOf("=");
					if (j != -1) {
						cookies.put(aCookie.substring(0, j),aCookie.substring(j + 1));
					}
				}
			}
		}
	}
	
	/**
	 * Write this cookies to a url connection. The connection should not connect already.
	 * This method will verify that if the host of urlConn matches the host who sent this
	 * cookie. If true, then send out itself, otherwise do nothing.
	 */
	public void writeCookies( URLConnection urlConn )  {
	
		if ( !cookies.isEmpty() ) {
			URL url = urlConn.getURL();
			String targetHost = url.getHost();
			//test if the target host match the source host
			if ( targetHost.equals( srcHost )) {
				String cookieString = getCookieString();
				if(IaaDebug.AuxDebug)IaaUtil.log("send cookies to "+ srcHost +" cookie: " + cookieString );
				urlConn.setRequestProperty("Cookie", cookieString );
			} else  {
				if(IaaDebug.AuxDebug)IaaUtil.log( "host not match error: cookie from: "+ srcHost +" now to: " + targetHost);
			}
			
		}
	}

	/**
	 * Test if this simple cookie has no content.
	 */
	public boolean isEmpty() {
		return cookies.isEmpty();
	}
	
	/**
	 * Get the the name of host who sent us this cookie.
	 */
	public String getHost() {
		return srcHost;
	}
	
	/**
	 * Return all the cookies as a single string.
	 */
	public String getCookieString() {
	
		StringBuffer strBuffer = new StringBuffer();
		strBuffer.append("");
			
		Enumeration keys = cookies.keys();
		while (keys.hasMoreElements()) {
			String key = (String) keys.nextElement();
			strBuffer.append( key );
			strBuffer.append("=");
			String value = (String) cookies.get(key);
			strBuffer.append( value );
			if (keys.hasMoreElements()) strBuffer.append("; ");
		}
		return strBuffer.toString();
	}
	
	/**
	 * A debug method which print out all the cookies to the stdout
	 */
	public void list() {
	
		StringBuffer strBuffer = new StringBuffer();
		strBuffer.append("");
		Enumeration keys = cookies.keys();
		while (keys.hasMoreElements()) {
			String key = (String) keys.nextElement();
			strBuffer.append( "cookie  name [" );
			strBuffer.append( key );
			strBuffer.append( "]  value [" );
			String value = (String) cookies.get(key);
			strBuffer.append( value );
			strBuffer.append( "]" );
			if (keys.hasMoreElements()) strBuffer.append("\n");
		}
		IaaUtil.log( "print out all the cookies :"+ strBuffer.toString()) ;
	}
}

